package com.heima.admin.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.utils.common.AdminIdThreadLocalUtil;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/16 10:08
 * @Version 1.0
 */
@Slf4j
@Component
public class AdTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String adminId = request.getHeader("adminId");
        log.info("Retrieved adminId: {}", adminId);

        if (StringUtils.isNotBlank(adminId)) {
            try {
                AdminIdThreadLocalUtil.setUser(Integer.parseInt(adminId));
            } catch (NumberFormatException e) {
                log.error("admin id 类型出错 {}", adminId, e);
            }
        } else {
            log.warn("未找到 admin id {}", this.getClass().getName());
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminIdThreadLocalUtil.remove();
    }
}
